/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ligacaoBD;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.management.Query;

/**
 *
 * @author JoséRego
 */
public class BDconnection {

    Connection connection;
    Statement stmt;
    PreparedStatement prStmt;
    ResultSet rs;
    String url = "jdbc:mysql://localhost:3306/gofast";
    String user = "root";
    String password = "admin";

    public ResultSet runQuery(String query) {

        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(url + "?user=" + user + "&password=" + password);
            stmt = connection.createStatement();
            rs = stmt.executeQuery(query);

        } catch (Exception e) {
            System.out.println(e);
        }
        return rs;
    }

    public BDconnection() {
    }

    public boolean executeUpdate(String[] query) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(url + "?user=" + user + "&password=" + password);
            StringBuilder sb = new StringBuilder();
            sb.append(query[0]).append("values (");
            for (int i = 1; i < query.length; i++) {
                sb.append("?,");
                if (i == query.length - 1) {
                    sb.append("?)");
                }
            }

            prStmt = connection.prepareStatement(sb.toString());
            for (int i = 1; i < query.length; i++) {
                prStmt.setString(i + 1, query[i]);
            }
            prStmt.executeUpdate();
        } catch (Exception e) {
            System.out.println(e);
            return false;
        }
        return true;
    }

    public void close() {
        try {
            if (rs != null) {
                rs.close();
            }

            if (stmt != null) {
                stmt.close();
            }

            if (connection != null) {
                connection.close();
            }
        } catch (Exception e) {
        }
    }
}
